import os
import re
import io
from PIL import Image


def re_filter(content_str):
    """
    用正则表达式过滤字符串，连续的空格等
    :param content_str:
    :return: 过滤后的content_str
    """
    content_str = re.sub('[\\t\\r ]{2,}', r' ', content_str)
    content_str = re.sub('\n{2,}', '\n', content_str)
    return content_str.strip()


def traverse_dir(path, tails, file_info_ls=None):
    """

    :param path:
    :param tails:
    :param file_info_ls:
    :return: [(文件路径1，文件名1),(文件路径2，文件名2),(文件路径3，文件名3),...,(文件路径n，文件名n)]
    注意：如路经太深python就无法检测该文件了，遇到这种情况请开启 clean_path功能；
    参考： https://blog.csdn.net/baidu_34928905/article/details/131935428
    """
    path = path
    if file_info_ls is None:
        file_info_ls = set()
    for file in os.listdir(path):
        file_path = os.path.join(path, file)
        if os.path.isdir(file_path):
            traverse_dir(file_path, tails, file_info_ls)
        else:
            file_e_ls = os.path.basename(file_path).split('.')
            file_tail = file_e_ls[-1]
            if (tails is None or file_tail.lower() in tails) and not os.path.basename(file_path).startswith('~$'):
                item = (file_path, '.'.join(file_e_ls[0:-1]))
                file_info_ls.add(item)
    return file_info_ls


def combine_images(images, saved_path='combined_image.jpg'):
    # 加载并过滤图片，只保留符合高度要求的图片
    images = [Image.open(io.BytesIO(img_blob)) for img_blob, suffix in images]
    max_height = max(i.height for i in images)
    images = [i for i in images if i.height >= max_height * 0.7]

    # 计算总宽度和最高高度
    total_width = sum(i.width for i in images)
    new_img = Image.new('RGB', (total_width, max_height))

    # 按顺序粘贴每张图片
    x_offset = 0
    for img in images:
        new_img.paste(img, (x_offset, 0))
        x_offset += img.width

    # 保存最终拼接图
    new_img.save(saved_path)


def img_to_png(blob, saved_path):
    with Image.open(io.BytesIO(blob)) as img:
        img.save(saved_path, 'PNG')
